package org.bdware.bdoa.authentication.serviceImpl;

import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.RSAKey;
import org.bdware.bdoa.authentication.JwtConfig;
import org.bdware.bdoa.authentication.exception.JwxException;
import org.bdware.bdoa.authentication.service.JwtService;
import org.bdware.bdoa.authentication.utils.JwxUtils;

import java.text.ParseException;

//基于非对称加密来生成和解析JWT令牌
public class RSAJwtServiceImpl implements JwtService {

    private JwtConfig jwtConfig;

    private RSAKey rsaKey;

    public RSAJwtServiceImpl(JwtConfig jwtConfig) {
        this.jwtConfig = jwtConfig;
    }

    @Override
    public RSAKey genKey() {
        if (rsaKey != null) {
            return rsaKey;
        }
        String key = jwtConfig.getRsaKey();
        if (JwxUtils.isEmpty(key)) {
            throw new JwxException(JwxUtils.KEY_GEN_ERROR, new NullPointerException("RSA need a key"));
        }
        JWK jwk = null;
        try {
            jwk = JWK.parse(key);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new JwxException(JwxUtils.KEY_GEN_ERROR);
        }
        RSAKey rsaJWK = jwk.toRSAKey();
        return rsaJWK;
    }

    @Override
    public String sign(String payload) {
        return JwxUtils.signClaimByRSA(payload, genKey(), jwtConfig);
    }

    @Override
    public String verify(String publicKeyStr, String token) {
        return JwxUtils.verifyClaimByRSA(token, genKey(), jwtConfig);
    }

    @Override
    public String verify(String publicKeyStr, String source, String token) {
        return null;
    }
}